#include "WebMonitor.h"


WebMonitor::WebMonitor(Client* evtHandler,RemoteHandle* remoteHandle) :
    _evtHandler(evtHandler),
    _remoteHandle(remoteHandle)
{
    oatpp::base::Environment::init();
}

WebMonitor::~WebMonitor()
{
    if(uploadThread.joinable())
    {
        _remoteHandle->closeTask();
        uploadThread.join();
    }
    oatpp::base::Environment::destroy();
}

const int32_t deviceLogin=0x4;
void WebMonitor::LoginServer()
{
    if(IPAddress.length()==0 || Port.length()==0 || DeviceName.length()==0)
    {
        throw std::runtime_error("请先设置服务器参数");
        return;
    }
    if(uploadThread.joinable())
    {
        _remoteHandle->closeTask();
        uploadThread.join();
    }
    auto connectionProvider = oatpp::network::tcp::client::ConnectionProvider::createShared({IPAddress, (uint16_t)std::stoi(Port)});
    auto connector = oatpp::websocket::Connector::createShared(connectionProvider);
    bool connectStatus=false;
    do
    {
        try
        {
            auto connection = connector->connect("CameraConnect");
            socket = oatpp::websocket::WebSocket::createShared(connection, true);
            socket->setListener(std::make_shared<WSMonitor>(socketWriteMutex,_evtHandler,_remoteHandle));
            connectStatus=false;
        }
        catch(const std::exception& e)
        {
            connectStatus=true;
            std::this_thread::sleep_for(std::chrono::seconds(2));
        }
    }while(connectStatus);
    
    uploadExitFlag=false;
    connectFlag=true;
    uploadThread=std::thread(&WebMonitor::UploadTask,this);
    {
        std::string loginData;
        loginData.append((char*)&deviceLogin,sizeof(int32_t));
        loginData.append(DeviceName);
        socket->sendOneFrameBinary(loginData);
        _remoteHandle->SetSocket(socket);
    }
    loginSuccess=true;
    socket->listen();
}

void WebMonitor::UploadTask()
{
    while (true)
    {
        try
        {
            socket->sendOneFrameBinary(_remoteHandle->SendData());
            if(_remoteHandle->FileTransferFuncEnable())
                _remoteHandle->SendFileData(socket);
        }
        catch(const std::exception& e)
        {
            return;
        }
    }
}

void WebMonitor::ListenTask()
{
    socket->listen();
    connectFlag.store(false);
}

bool WebMonitor::GetConnectStatus()
{
    return connectFlag;
}

bool WebMonitor::SetServerConfig(std::string _IPaddr,std::string _Port,std::string _DeviceName)
{
    IPAddress=_IPaddr;
    Port=_Port;
    DeviceName=_DeviceName;
    return true;
}

bool WebMonitor::GetLoginStatus()
{
    return loginSuccess;
}